# -*- encoding: utf-8 -*-
import socket
from threading import Thread


class Server:
    def __init__(self):
        # 初始化服务端socket
        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # 设置服务端ip和port
        self.server_address = (self.get_addr(), 8080)
        # 客户端连接的新套接字
        self.client_sockets = []

    def start(self):
        # 绑定ip和port
        self.server_socket.bind(self.server_address)
        # 开启监听，最大并发8台设备
        self.server_socket.listen(8)
        print(f"Server is listening at {self.get_addr()}:{8080}")

        while True:
            # 等待客户端的连接
            # connection 客户端的新套接字
            # client_address 客户端的ip和port
            connection, client_address = self.server_socket.accept()
            # 将客户端的新套接字加入到客户端套接字列表中
            self.client_sockets.append(connection)
            # 开启线程持续收发消息
            Thread(target=self.worker, args=(connection,)).start()

    def worker(self, con):
        """ 收发处理每个客户端的数据 """
        while True:
            try:
                # 接受客户端发来的数据
                recv_data = con.recv(512)
                print("CLIENT RECV DATA:", recv_data)
                
                if recv_data:
                # 向每个连接的客户端发送数据
                    for s in self.client_sockets:
                        s.send(recv_data)
            except ConnectionResetError:
                self.client_sockets.remove(con)
                # 关闭客户端套接字 清理连接
                con.close()
                break

    def get_addr(self):
        return socket.gethostbyname(socket.gethostname())


if __name__ == '__main__':
    s = Server()
    s.start()
